<!-- AddDepartment.vue -->
<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const departmentName = ref('')
const errorMessage = ref('')

const isValid = computed(() => {
  return departmentName.value.trim() !== '' && errorMessage.value === ''
})

const validateInput = () => {
  const name = departmentName.value.trim()
  if (!name) {
    errorMessage.value = '部门名称不能为空'
  } else if (name.length > 50) {
    errorMessage.value = '部门名称不能超过50个字符'
  } else {
    errorMessage.value = ''
  }
}

const handleSubmit = async () => {
  validateInput()
  if (!isValid.value) return

  try {
    // 构造部门数据
    const departmentData = [{
      departmentId: null, // 部门编号为空，由后端自动生成
      departmentName: departmentName.value.trim()
    }]

    // 调用后端接口
    const response = await axios.post(
      'http://127.0.0.1:8080/admin/department/add',
      departmentData,
      {
        headers: {
          'Content-Type': 'application/json',
          token: localStorage.getItem('token') // 如果需要token验证
        }
      }
    )

    const result = response.data
    if (result.code === 200) {
      alert('部门添加成功')
      handleCancel()
    } else {
      ElMessage.error(result.message || '部门添加失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('部门添加失败，请检查网络连接')
  }
}

const handleCancel = () => {
  departmentName.value = ''
  errorMessage.value = ''
}
</script>
<template>
  <div class="min-h-screen bg-gray-50 py-8">
    <div class="max-w-2xl mx-auto bg-white rounded-lg shadow-sm">
      <!-- 标题区域 -->
      <div class="px-8 py-6 border-b border-gray-200">
        <h1 class="text-2xl font-medium text-gray-900">添加部门</h1>
      </div>

      <!-- 表单区域 -->
      <div class="px-8 py-6">
        <el-form @submit.prevent class="space-y-6">
          <el-form-item
            label="部门名称"
            :error="errorMessage"
            class="w-full"
            label-width="80px"
          >
            <el-input
              v-model="departmentName"
              placeholder="请输入部门名称"
              @blur="validateInput"
            />
          </el-form-item>

          <!-- 按钮区域 -->
          <div class="mt-8 flex items-center justify-end space-x-4">
            <el-button @click="handleCancel">取消</el-button>
            <el-button
              type="primary"
              :disabled="!isValid"
              @click="handleSubmit"
            >
              确定
            </el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>
